package com.yzt.message;

import android.net.Uri;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.yzt.zhuju.config.AppConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import io.rong.common.RLog;
import io.rong.imkit.IMCenter;
import io.rong.imkit.R.string;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.RongIMClient.ErrorCode;
import io.rong.imlib.RongIMClient.SendImageMessageCallback;
import io.rong.imlib.model.Conversation.ConversationType;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.Message.SentStatus;
import io.rong.imlib.model.MessageContent;
import io.rong.message.GIFMessage;
import io.rong.message.ImageMessage;

public class MySendImageManager {

    private ExecutorService executorService;
    private final MySendImageManager.UploadController uploadController;

    public static MySendImageManager getInstance() {
        return MySendImageManager.SingletonHolder.sInstance;
    }

    private MySendImageManager() {
        this.executorService = this.getExecutorService();
        this.uploadController = new MySendImageManager.UploadController();
    }

    public void sendImages(ConversationType conversationType, String targetId, List<Uri> imageList, boolean isFull) {
        this.sendImages(conversationType, targetId, imageList, isFull, false, 0L);
    }

    public void sendImages(ConversationType conversationType, String targetId, List<Uri> imageList, boolean isFull, boolean isDestruct, long destructTime) {
        this.sendImages(conversationType, targetId, imageList, isFull, false, 0L, "");
    }

    public void sendImages(ConversationType conversationType, String targetId, List<Uri> imageList,
                           boolean isFull, boolean isDestruct, long destructTime, String extra) {
        RLog.d("SendImageManager", "sendImages " + imageList.size());

        for (Uri image : imageList) {
            if (!TextUtils.isEmpty(image.getPath())) {
                File file = new File(image.getPath());
                if (file.exists() && image.getPath() != null) {
                    Object content;
                    if (image.getPath().endsWith("gif")) {
                        GIFMessage gifMessage = GIFMessage.obtain(image);
                        gifMessage.setExtra(extra);
                        content = gifMessage;
                    } else {
                        ImageMessage imageMessage = ImageMessage.obtain(image, image, isFull);
                        imageMessage.setExtra(extra);
                        content = imageMessage;
                    }

                    if (isDestruct && content != null) {
                        ((MessageContent) content).setDestructTime(destructTime);
                    }

                    IMCenter.getInstance().insertOutgoingMessage(conversationType, targetId, SentStatus.SENDING, (MessageContent) content, new RongIMClient.ResultCallback<Message>() {
                        @Override
                        public void onSuccess(Message message) {
                            MySendImageManager.this.uploadController.execute(message);
                        }

                        @Override
                        public void onError(ErrorCode errorCode) {
                        }
                    });
                }
            }
        }
    }

    public void cancelSendingImages(ConversationType conversationType, String targetId) {
        RLog.d("SendImageManager", "cancelSendingImages");
        if (conversationType != null && targetId != null && this.uploadController != null) {
            this.uploadController.cancel(conversationType, targetId);
        }
    }

    public void cancelSendingImage(ConversationType conversationType, String targetId, int messageId) {
        RLog.d("SendImageManager", "cancelSendingImages");
        if (conversationType != null && targetId != null && this.uploadController != null && messageId > 0) {
            this.uploadController.cancel(conversationType, targetId, messageId);
        }
    }

    public void reset() {
        this.uploadController.reset();
    }

    private ExecutorService getExecutorService() {
        if (this.executorService == null) {
            this.executorService = new ThreadPoolExecutor(1, 2147483647, 60L, TimeUnit.SECONDS, new SynchronousQueue(), this.threadFactory());
        }

        return this.executorService;
    }

    private ThreadFactory threadFactory() {
        return new ThreadFactory() {
            @Override
            public Thread newThread(@Nullable Runnable runnable) {
                Thread result = new Thread(runnable, "Rong SendMediaManager");
                result.setDaemon(false);
                return result;
            }
        };
    }

    private class UploadController implements Runnable {
        final List<Message> pendingMessages = new ArrayList();
        Message executingMessage;

        public UploadController() {

        }

        public void execute(Message message) {
            synchronized (this.pendingMessages) {
                this.pendingMessages.add(message);
                if (this.executingMessage == null) {
                    this.executingMessage = this.pendingMessages.remove(0);
                    MySendImageManager.this.executorService.submit(this);
                }
            }
        }

        public void reset() {
            RLog.w("SendImageManager", "Rest Sending Images.");
            synchronized (this.pendingMessages) {
                Iterator var2 = this.pendingMessages.iterator();

                while (true) {
                    if (!var2.hasNext()) {
                        this.pendingMessages.clear();
                        break;
                    }

                    Message message = (Message) var2.next();
                    message.setSentStatus(SentStatus.FAILED);
                }
            }

            if (this.executingMessage != null) {
                this.executingMessage.setSentStatus(SentStatus.FAILED);
                this.executingMessage = null;
            }

        }

        public void cancel(ConversationType conversationType, String targetId) {
            synchronized (this.pendingMessages) {
                Iterator it = this.pendingMessages.iterator();

                while (it.hasNext()) {
                    Message msg = (Message) it.next();
                    if (msg.getConversationType().equals(conversationType) && msg.getTargetId().equals(targetId)) {
                        it.remove();
                    }
                }

                if (this.pendingMessages.size() == 0) {
                    this.executingMessage = null;
                }
            }
        }

        public void cancel(ConversationType conversationType, String targetId, int messageId) {
            synchronized (this.pendingMessages) {
                int count = this.pendingMessages.size();

                for (int i = 0; i < count; ++i) {
                    Message msg = this.pendingMessages.get(i);
                    if (msg.getConversationType().equals(conversationType) && msg.getTargetId().equals(targetId) && msg.getMessageId() == messageId) {
                        this.pendingMessages.remove(msg);
                        break;
                    }
                }

                if (this.pendingMessages.size() == 0) {
                    this.executingMessage = null;
                }
            }
        }

        private void polling() {
            synchronized (this.pendingMessages) {
                RLog.d("SendImageManager", "polling " + this.pendingMessages.size());
                if (this.pendingMessages.size() > 0) {
                    this.executingMessage = this.pendingMessages.remove(0);
                    MySendImageManager.this.executorService.submit(this);
                } else {
                    this.executingMessage = null;
                }
            }
        }

        @Override
        public void run() {
            boolean isDestruct = false;
            if (this.executingMessage.getContent() != null) {
                isDestruct = this.executingMessage.getContent().isDestruct();
            }

            RongIMClient.getInstance().sendImageMessage(this.executingMessage, isDestruct ? AppConfig.context.getString(string.rc_message_content_burn) : null, null, new SendImageMessageCallback() {
                @Override
                public void onAttached(Message message) {
                }

                @Override
                public void onError(Message message, ErrorCode code) {
                    MySendImageManager.UploadController.this.polling();
                }

                @Override
                public void onSuccess(Message message) {
                    MySendImageManager.UploadController.this.polling();
                }

                @Override
                public void onProgress(Message message, int progress) {
                }
            });
        }
    }

    static class SingletonHolder {

        static MySendImageManager sInstance = new MySendImageManager();

        SingletonHolder() {

        }
    }
}
